package com.sikaryofficial.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.utils.poi.ExcelUtil;
import com.sikaryofficial.common.core.web.controller.BaseController;
import com.sikaryofficial.common.core.web.page.TableDataInfo;
import com.sikaryofficial.common.log.annotation.Log;
import com.sikaryofficial.common.log.enums.BusinessType;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.system.api.model.SysMemberReq;
import com.sikaryofficial.system.config.HiSMKAuthConfig;
import com.sikaryofficial.system.domain.PointsBalance;
import com.sikaryofficial.system.domain.dto.SysMemberUserListDTO;
import com.sikaryofficial.system.domain.dto.SysMemberUserListReq;
import com.sikaryofficial.system.service.IPointBalanceService;
import com.sikaryofficial.system.service.ISysMemberUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 会员管理
 *
 * @author qinjinyuan
 */
@RestController
@RequestMapping("/member")
@Api(tags = "会员管理")
public class SysMemberUserController extends BaseController {
    @Autowired
    private ISysMemberUserService memberUserService;
    @Autowired
    private IPointBalanceService pointBalanceService;

    @Autowired
    private RedisService redisService;

    @Resource
    private HiSMKAuthConfig authConfig;

    @PostMapping("/list")
    @ApiOperation(value = "会员列表")
    @JsonFormat
    public TableDataInfo list(@RequestBody SysMemberUserListReq req) {
        startPage(req.getPageNum(), req.getPageSize());
        req.setDeptId(authConfig.getDefaultDeptId());
        List<SysMemberUserListDTO> list = memberUserService.selectMemberUserList(req);
        // 构建积分数据
        buildPoints(list);
        // 设置序号
        AtomicInteger rowNum = new AtomicInteger(1);
        list.forEach(item -> {
            item.setSeqNo((req.getPageNum() - 1) * req.getPageSize() + rowNum.get());
            rowNum.getAndIncrement();
        });
        return getDataTable(list);
    }


    @Log(title = "会员管理-导出", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "会员管理-导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody SysMemberReq req) {
        SysMemberUserListReq req1 = new SysMemberUserListReq();
        req1.setDeptId(authConfig.getDefaultDeptId());
        List<Long> userIds = Lists.newArrayList();
        if (req.getUserIds() != null && !req.getUserIds().isEmpty()) {
            Arrays.asList(req.getUserIds().split(",")).forEach(userId -> userIds.add(Long.valueOf(userId)));
            req1.setUserIds(userIds);
        }
        if (CollUtil.isEmpty(userIds)) {
            throw new ServiceException("请选择要导出的会员");
        }
        List<SysMemberUserListDTO> list = memberUserService.selectMemberUserList(req1);
        // 构建积分数据
        buildPoints(list);
        // 设置序号
        AtomicInteger rowNum = new AtomicInteger(1);
        list.forEach(item -> {
            item.setSeqNo(rowNum.get());
            rowNum.getAndIncrement();
            item.setFirstNameAndLastName(item.getFirstName() + "." + item.getLastName());
            if (Objects.nonNull(item.getBirthDate())) {
                item.setAge(LocalDateTimeUtil.of(new Date()).getYear() - LocalDateTimeUtil.of(item.getBirthDate()).getYear());
            }
        });
        ExcelUtil<SysMemberUserListDTO> util = new ExcelUtil<SysMemberUserListDTO>(SysMemberUserListDTO.class);
        util.exportExcel(response, list, "会员数据");
    }

    /**
     * 构建积分数据
     *
     * @param list
     */
    private void buildPoints(List<SysMemberUserListDTO> list) {
        if (CollUtil.isNotEmpty(list)) {
            Map<Long, PointsBalance> pointsBalanceMap = pointBalanceService.selectMapByUserIds(list.stream().map(SysMemberUserListDTO::getUserId).collect(Collectors.toList()));
            for (SysMemberUserListDTO userListDTO : list) {
                PointsBalance pointsBalance = MapUtils.getObject(pointsBalanceMap, userListDTO.getUserId());
                if(Objects.isNull(pointsBalance)){
                    continue;
                }
                userListDTO.setPoints(pointsBalance.getBalance());
            }
        }
    }

}
